package com.reactim.message.controller;

import com.reactim.message.metrics.ConnectionPerformanceMetrics;
import com.reactim.message.performance.PerformanceOptimizer;
import com.reactim.common.response.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 性能监控控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/performance")
@RequiredArgsConstructor
public class PerformanceController {

    private final ConnectionPerformanceMetrics performanceMetrics;
    private final PerformanceOptimizer performanceOptimizer;

    /**
     * 获取性能监控报告
     */
    @GetMapping("/report")
    public Result<ConnectionPerformanceMetrics.PerformanceReport> getPerformanceReport() {
        try {
            ConnectionPerformanceMetrics.PerformanceReport report = performanceMetrics.getPerformanceReport();
            return Result.success(report);
        } catch (Exception e) {
            log.error("获取性能报告失败", e);
            return Result.error("获取性能报告失败: " + e.getMessage());
        }
    }

    /**
     * 获取性能优化分析
     */
    @GetMapping("/analysis")
    public Result<PerformanceOptimizer.OptimizationReport> getPerformanceAnalysis() {
        try {
            PerformanceOptimizer.OptimizationReport analysis = performanceOptimizer.analyzePerformance();
            return Result.success(analysis);
        } catch (Exception e) {
            log.error("获取性能分析失败", e);
            return Result.error("获取性能分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取性能分析摘要
     */
    @GetMapping("/summary")
    public Result<String> getPerformanceSummary() {
        try {
            PerformanceOptimizer.OptimizationReport analysis = performanceOptimizer.analyzePerformance();
            String summary = analysis.generateSummary();
            return Result.success(summary);
        } catch (Exception e) {
            log.error("获取性能摘要失败", e);
            return Result.error("获取性能摘要失败: " + e.getMessage());
        }
    }

    /**
     * 重置性能统计数据
     */
    @PostMapping("/reset")
    public Result<String> resetPerformanceMetrics() {
        try {
            performanceMetrics.reset();
            log.info("性能统计数据已重置");
            return Result.success("性能统计数据已重置");
        } catch (Exception e) {
            log.error("重置性能统计数据失败", e);
            return Result.error("重置失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前连接统计
     */
    @GetMapping("/connections")
    public Result<ConnectionStats> getConnectionStats() {
        try {
            ConnectionPerformanceMetrics.PerformanceReport report = performanceMetrics.getPerformanceReport();
            
            ConnectionStats stats = ConnectionStats.builder()
                    .currentConnections(report.getCurrentConnections())
                    .totalCreated(report.getTotalConnectionsCreated())
                    .totalRemoved(report.getTotalConnectionsRemoved())
                    .storeOperations(report.getStoreOperationCount())
                    .retrieveOperations(report.getRetrieveOperationCount())
                    .removeOperations(report.getRemoveOperationCount())
                    .storeErrors(report.getStoreErrorCount())
                    .retrieveErrors(report.getRetrieveErrorCount())
                    .build();
            
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取连接统计失败", e);
            return Result.error("获取连接统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取延迟统计
     */
    @GetMapping("/latency")
    public Result<LatencyStats> getLatencyStats() {
        try {
            ConnectionPerformanceMetrics.PerformanceReport report = performanceMetrics.getPerformanceReport();
            
            LatencyStats stats = LatencyStats.builder()
                    .averageStoreTime(report.getAverageStoreTime())
                    .averageRetrieveTime(report.getAverageRetrieveTime())
                    .averageRemoveTime(report.getAverageRemoveTime())
                    .storeLatencyP50(report.getStoreLatencyP50())
                    .storeLatencyP95(report.getStoreLatencyP95())
                    .storeLatencyP99(report.getStoreLatencyP99())
                    .retrieveLatencyP50(report.getRetrieveLatencyP50())
                    .retrieveLatencyP95(report.getRetrieveLatencyP95())
                    .retrieveLatencyP99(report.getRetrieveLatencyP99())
                    .build();
            
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取延迟统计失败", e);
            return Result.error("获取延迟统计失败: " + e.getMessage());
        }
    }

    // 数据结构定义
    @lombok.Data
    @lombok.Builder
    public static class ConnectionStats {
        private long currentConnections;
        private long totalCreated;
        private long totalRemoved;
        private double storeOperations;
        private double retrieveOperations;
        private double removeOperations;
        private double storeErrors;
        private double retrieveErrors;
    }

    @lombok.Data
    @lombok.Builder
    public static class LatencyStats {
        private double averageStoreTime;
        private double averageRetrieveTime;
        private double averageRemoveTime;
        private double storeLatencyP50;
        private double storeLatencyP95;
        private double storeLatencyP99;
        private double retrieveLatencyP50;
        private double retrieveLatencyP95;
        private double retrieveLatencyP99;
    }
}